<template>
  <view class="order-detail-page">
    <!-- 订单状态 -->
    <view class="order-status-bar">
      <view class="status-text" :class="getStatusConfig(order.status).class">
        {{ getStatusConfig(order.status).text }}
      </view>
      <view class="status-desc" v-if="order.status === 1">
        请在 {{ formatTime(order.expireTime) }} 前完成支付，超时订单将自动取消
      </view>
    </view>

    <!-- 订单信息卡片 -->
    <view class="order-card">
      <!-- 商家信息 -->
      <view class="card-section">
        <view class="section-title">商家信息</view>
        <view class="seller-info">
          <uni-icons type="shop" size="18" color="#666" class="seller-icon"></uni-icons>
          <text class="seller-name">{{ order.sellerName || '未知商家' }}</text>
          <button class="contact-btn" @click="contactSeller">联系商家</button>
        </view>
      </view>

      <!-- 商品信息 -->
      <view class="card-section">
        <view class="section-title">商品信息</view>
        <view class="goods-info" @click="goToGoodsDetail(order.itemId)">
          <view class="goods-image-wrapper">
            <image
                class="goods-image"
                :src="getFirstImage(order.itemImage)"
                mode="aspectFill"
            ></image>
          </view>
          <view class="goods-details">
            <view class="goods-title">{{ order.itemName || '商品名称' }}</view>
            <view class="goods-spec">{{ order.description || '无商品描述' }}</view>
            <view class="goods-price">¥{{ order.totalAmount || 0 }}</view>
          </view>
          <view class="goods-count">x1</view>
        </view>
      </view>

      <!-- 商品图片预览 -->
      <view class="card-section" v-if="getImageList(order.itemImage).length > 1">
        <view class="section-title">商品图片</view>
        <view class="image-preview">
          <view
              class="preview-item"
              v-for="(img, index) in getImageList(order.itemImage)"
              :key="index"
              @click="previewImage(img, getImageList(order.itemImage))"
          >
            <image :src="img" mode="aspectFill"></image>
          </view>
        </view>
      </view>

      <!-- 订单信息 -->
      <view class="card-section">
        <view class="section-title">订单信息</view>
        <view class="info-item">
          <view class="info-label">订单编号</view>
          <view class="info-value">{{ order.orderNumber }}</view>
        </view>
        <view class="info-item">
          <view class="info-label">创建时间</view>
          <view class="info-value">{{ formatTime(order.createTime) }}</view>
        </view>
        <view class="info-item" v-if="order.paymentTime">
          <view class="info-label">支付时间</view>
          <view class="info-value">{{ formatTime(order.paymentTime) }}</view>
        </view>
        <view class="info-item" v-if="order.status === 1">
          <view class="info-label">过期时间</view>
          <view class="info-value">{{ formatTime(order.expireTime) }}</view>
        </view>
        <view class="info-item" v-if="order.updateTime">
          <view class="info-label">更新时间</view>
          <view class="info-value">{{ formatTime(order.updateTime) }}</view>
        </view>
      </view>

      <!-- 金额信息 -->
      <view class="card-section">
        <view class="section-title">金额信息</view>
        <view class="info-item">
          <view class="info-label">商品总价</view>
          <view class="info-value">¥{{ order.totalAmount || 0 }}</view>
        </view>
        <view class="info-item">
          <view class="info-label">优惠券抵扣</view>
          <view class="info-value">-¥{{ order.couponAmount || 0 }}</view>
        </view>
        <view class="info-item total-amount">
          <view class="info-label">实付金额</view>
          <view class="info-value">¥{{ calculateActualPayment }}</view>
        </view>
      </view>

      <!-- 配送和支付方式 -->
      <view class="card-section">
        <view class="section-title">配送与支付</view>
        <view class="info-item">
          <view class="info-label">配送方式</view>
          <view class="info-value">{{ getShippingMethodText(order.shippingMethod) }}</view>
        </view>
        <view class="info-item">
          <view class="info-label">支付方式</view>
          <view class="info-value">{{ order.paymentMethod ? getPaymentMethodText(order.paymentMethod) : '微信支付' }}</view>
        </view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="action-bar">
      <button
          class="action-btn cancel-btn"
          v-if="order.status === 1"
          @click="cancelOrder(order.orderNumber)"
      >
        取消订单
      </button>
      <button
          class="action-btn pay-btn"
          v-if="order.status === 1"
          @click="payOrder(order.id)"
      >
        去付款
      </button>
      <button
          class="action-btn confirm-btn"
          v-if="order.status === 2 || order.status === 3"
          @click="confirmReceipt(order.id)"
      >
        确认收货
      </button>
      <button
          class="action-btn comment-btn"
          v-if="order.status === 4"
          @click="goToComment(order.id)"
      >
        去评价
      </button>
      <button
          class="action-btn detail-btn"
          v-if="order.status === 5 || order.status === 6"
          @click="onBack"
      >
        返回列表
      </button>
    </view>

    <!-- 加载状态 -->
    <view class="loading-state" v-if="loading">
      <uni-loading-icon size="24" color="#ff4d4f"></uni-loading-icon>
      <text class="loading-text">加载中...</text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { cancelOrderApi, confirmOrder, selectOrder } from "@/apis/orderApi";

// 订单状态配置（与myorder页面保持一致）
// 状态定义：1-待支付, 2-已支付, 3-已发货, 4-已完成, 5-已取消, 6-已评价
const ORDER_STATUS_CONFIG = {
  1: { key: 'unpaid', text: '待支付', class: 'unpaid', sortWeight: 1 },
  2: { key: 'paid', text: '已支付', class: 'paid', sortWeight: 2 },
  3: { key: 'shipped', text: '已发货', class: 'shipped', sortWeight: 3 },
  4: { key: 'completed', text: '已完成', class: 'completed', sortWeight: 4 },
  5: { key: 'cancelled', text: '已取消', class: 'cancelled', sortWeight: 6 },
  6: { key: 'commented', text: '已评价', class: 'commented', sortWeight: 5 }
};

// 配送方式配置
const SHIPPING_METHOD = {
  1: '普通快递',
  2: '顺丰速运',
  3: '京东物流',
  4: '到店自提'
};

// 支付方式配置（与myorder页面逻辑匹配）
const PAYMENT_METHOD = {
  1: '微信支付',
  2: '支付宝',
  3: '钱包支付', // 与myorder的支付方式对应
  4: '货到付款'
};

// 响应式数据
const order = ref({});
const loading = ref(true);
const orderId = ref('');

// 获取页面参数
onMounted(() => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  orderId.value = currentPage.options.orderId || '';
  if (orderId.value) {
    fetchOrderDetail();
  } else {
    uni.showToast({ title: '订单ID不存在', icon: 'none' });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  }
});

// 获取订单详情（复用myorder的订单查询接口）
const fetchOrderDetail = async () => {
  try {
    loading.value = true;
    const res = await selectOrder(orderId.value);
    if (res.data.code === 200) {
      order.value = res.data.data;
    } else {
      uni.showToast({ title: res.data.msg || '获取订单详情失败', icon: 'none' });
    }
  } catch (err) {
    console.error('获取订单详情失败:', err);
    uni.showToast({ title: '网络错误，请重试', icon: 'none' });
  } finally {
    loading.value = false;
  }
};

// 获取状态配置信息（与myorder统一）
const getStatusConfig = (status) => {
  return ORDER_STATUS_CONFIG[status] || {
    text: '未知状态',
    class: 'unknown',
    sortWeight: 99
  };
};

// 处理商品图片（取第一张，与myorder逻辑一致）
const getFirstImage = (imageStr) => {
  try {
    const images = JSON.parse(imageStr || '[]');
    return images[0] || '/static/images/default-goods.png';
  } catch (e) {
    console.error('解析图片地址失败:', e);
    return '/static/images/default-goods.png';
  }
};

// 获取图片列表（用于预览）
const getImageList = (imageStr) => {
  try {
    return JSON.parse(imageStr || '[]');
  } catch (e) {
    console.error('解析图片地址失败:', e);
    return [];
  }
};

// 时间格式化（与myorder保持一致）
const formatTime = (dateString) => {
  if (!dateString) return '未知时间';
  const date = new Date(dateString);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
};

// 计算实付金额
const calculateActualPayment = computed(() => {
  const total = Number(order.value.totalAmount) || 0;
  const coupon = Number(order.value.couponAmount) || 0;
  return (total - coupon).toFixed(2);
});

// 获取配送方式文本
const getShippingMethodText = (method) => {
  return SHIPPING_METHOD[method] || '未知配送方式';
};

// 获取支付方式文本
const getPaymentMethodText = (method) => {
  return PAYMENT_METHOD[method] || '未知支付方式';
};

// 返回上一页
const onBack = () => uni.navigateBack();

// 预览图片
const previewImage = (current, urls) => {
  uni.previewImage({
    current,
    urls
  });
};

// 联系商家
const contactSeller = () => {
  uni.showToast({ title: '联系商家功能开发中', icon: 'none' });
};

// 去商品详情
const goToGoodsDetail = (itemId) => {
  if (itemId) {
    uni.navigateTo({ url: `/pages/shop/shop-detail?itemId=${itemId}` });
  }
};

// 取消订单（复用myorder的API）
const cancelOrder = (orderNumber) => {
  uni.showModal({
    title: '确认取消',
    content: '确定要取消该订单吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const res = await cancelOrderApi(orderNumber);
          if (res.data.code === 200) {
            uni.showToast({ title: '订单已取消', icon: 'success' });
            setTimeout(() => {
              onBack();
            }, 1500);
          } else {
            uni.showToast({ title: res.data.msg || '取消失败', icon: 'none' });
          }
        } catch (err) {
          console.error('取消订单失败:', err);
          uni.showToast({ title: '网络错误，请重试', icon: 'none' });
        }
      }
    }
  });
};

// 去付款（与myorder跳转路径一致）
const payOrder = (orderId) => {
  uni.navigateTo({ url: `/pages/shop/shop-play?orderId=${orderId}` });
};

// 去评价（对应myorder的已完成状态4）
const goToComment = (orderId) => {
  uni.navigateTo({ url: `/pages/shop/shop-comment?orderId=${orderId}` });
};

// 确认收货（复用myorder的API，状态与myorder一致：2-已支付/3-已发货）
const confirmReceipt = (orderId) => {
  uni.showModal({
    title: '确认收货',
    content: '请确认已收到商品，确认后订单状态将变为"已完成"',
    success: async (res) => {
      if (res.confirm) {
        try {
          const res = await confirmOrder(orderId);
          if (res.data.code === 200) {
            uni.showToast({ title: '确认收货成功', icon: 'success' });
            // 更新订单状态为已完成（状态4）
            order.value.status = 4;
          } else {
            uni.showToast({ title: res.data.msg || '操作失败', icon: 'none' });
          }
        } catch (err) {
          console.error('确认收货失败:', err);
          uni.showToast({ title: '网络错误，请重试', icon: 'none' });
        }
      }
    }
  });
};
</script>

<style scoped>
/* 复用myorder页面的CSS变量，保持样式统一 */
:root {
  --primary-color: #ff4d4f;
  --border-color: #f5f5f5;
  --text-primary: #333;
  --text-secondary: #666;
  --text-tertiary: #999;
  --gap-sm: 8px;
  --gap-md: 16px;
  --radius: 8px;
}

.order-detail-page {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  font-size: 14px;
  padding-bottom: 60px;
}

/* 订单状态栏（与myorder状态样式一致） */
.order-status-bar {
  background-color: #fff;
  padding: 16px;
  margin-bottom: 10px;
}

.status-text {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 8px;
  display: inline-block;
  padding: 2px 8px;
  border-radius: 12px;
}

/* 状态样式（与myorder保持一致） */
.status-text.unpaid {
  color: #fa8c16;
  background-color: #fff8f0; /* 待支付-橙色背景 */
}

.status-text.paid {
  color: #52c41a;
  background-color: #f6ffed; /* 已支付-绿色背景 */
}

.status-text.shipped {
  color: #1890ff;
  background-color: #e6f7ff; /* 已发货-蓝色背景 */
}

.status-text.completed {
  color: #722ed1;
  background-color: #f9f0ff; /* 已完成-紫色背景 */
}

.status-text.cancelled {
  color: #bfbfbf;
  background-color: #f5f5f5; /* 已取消-灰色背景 */
}

.status-text.commented {
  color: #ff4d4f;
  background-color: #fff1f0; /* 已评价-红色背景 */
}

.status-desc {
  font-size: 14px;
  color: var(--text-tertiary);
}

/* 订单卡片 */
.order-card {
  background-color: #fff;
  border-radius: var(--radius);
  margin: 0 var(--gap-md) var(--gap-md);
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 卡片 sections */
.card-section {
  padding: 16px;
  border-bottom: 1px solid var(--border-color);
}

.card-section:last-child {
  border-bottom: none;
}

.section-title {
  font-size: 16px;
  color: var(--text-primary);
  font-weight: 500;
  margin-bottom: 12px;
  padding-left: 4px;
  position: relative;
}

.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 3px;
  height: 16px;
  background-color: var(--primary-color);
  border-radius: 2px;
}

/* 商家信息 */
.seller-info {
  display: flex;
  align-items: center;
}

.seller-icon {
  margin-right: 8px;
}

.seller-name {
  flex: 1;
  font-size: 15px;
}

.contact-btn {
  height: 30px;
  line-height: 30px;
  padding: 0 12px;
  font-size: 14px;
  color: var(--primary-color);
  background-color: transparent;
  border: 1px solid var(--primary-color);
  border-radius: 4px;
}

/* 商品信息 */
.goods-info {
  display: flex;
  align-items: center;
}

.goods-image-wrapper {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  overflow: hidden;
  margin-right: 12px;
}

.goods-image {
  width: 100%;
  height: 100%;
}

.goods-details {
  flex: 1;
  min-width: 0;
}

.goods-title {
  font-size: 15px;
  color: var(--text-primary);
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.goods-spec {
  font-size: 13px;
  color: var(--text-tertiary);
  margin-bottom: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.goods-price {
  font-size: 15px;
  color: var(--primary-color);
  font-weight: 500;
}

.goods-count {
  font-size: 14px;
  color: var(--text-secondary);
}

/* 图片预览 */
.image-preview {
  display: flex;
  gap: 8px;
  overflow-x: auto;
  padding-bottom: 8px;
}

.preview-item {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  overflow: hidden;
  flex-shrink: 0;
}

.preview-item image {
  width: 100%;
  height: 100%;
}

/* 信息项 */
.info-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 4px;
}

.info-label {
  color: var(--text-secondary);
}

.info-value {
  color: var(--text-primary);
  text-align: right;
  word-break: break-all;
}

.total-amount .info-label {
  font-weight: 500;
}

.total-amount .info-value {
  color: var(--primary-color);
  font-weight: 500;
  font-size: 16px;
}

/* 操作栏（与myorder按钮样式一致） */
.action-bar {
  display: flex;
  gap: 10px;
  padding: 10px var(--gap-md);
  background-color: #fff;
  border-top: 1px solid var(--border-color);
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 10;
}

/* 按钮样式（与myorder保持一致） */
.action-btn {
  flex: 1;
  height: 40px;
  line-height: 40px;
  border-radius: 4px;
  font-size: 16px;
  border: none;
}

.cancel-btn {
  color: var(--text-secondary);
  background-color: var(--border-color);
}

.pay-btn {
  color: #fff;
  background-color: var(--primary-color);
}

.confirm-btn {
  color: #fff;
  background-color: #1890ff;
}

.comment-btn {
  color: #fff;
  background-color: #fa8c16;
}

.detail-btn {
  color: var(--text-secondary);
  background-color: #fff;
  border: 1px solid #ddd;
}

/* 加载状态 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100px 0;
  color: var(--text-tertiary);
  font-size: 14px;
}
</style>